package com.lingshu.app.ui.message;

import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.lingshu.app.R;
import com.lingshu.app.base.BaseFragment;
import com.lingshu.app.database.bean.MessageBean;
import com.lingshu.app.databinding.FragmentMessageBinding;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import dagger.hilt.android.AndroidEntryPoint;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/3 14:15
 * @Description
 */
@AndroidEntryPoint
public class MessageFragment extends BaseFragment<FragmentMessageBinding, MessageFragmentViewModel> {
    private MessageFragmentAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private List<MessageBean> dataList = new ArrayList<>();
    private int pageIndex = 1;
    private final int PAGE_SIZE = 15;
    private Integer totalPage;
    private Integer lastVisibleItem;

    /**
     * 获取当前页面的布局资源ID
     *
     * @return 布局资源ID
     */
    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_message;
    }

    /**
     * 初始化ViewModel
     */
    @Override
    protected void initViewModel() {
        viewModel = new ViewModelProvider(this).get(MessageFragmentViewModel.class);
    }

    /**
     * 绑定ViewModel
     */
    @Override
    protected void bindViewModel() {
        dataBinding.setViewModel(viewModel);
    }

    /**
     * 初始化
     */
    @Override
    protected void init() {
        initRecyclerView();
        initRefreshLayout();
        observerData();
        viewModel.initData();
        loadPageData(1);
    }

    /**
     * 下拉刷新
     */
    private void initRefreshLayout() {
        dataBinding.srlMessage.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        dataBinding.srlMessage.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取初始化数据
                loadPageData(1);
                dataBinding.srlMessage.setRefreshing(false);
            }
        });
    }

    /**
     * 加载列表数据
     */
    private void initRecyclerView() {
        linearLayoutManager = new LinearLayoutManager(context);
        adapter = new MessageFragmentAdapter(context, dataList) {
            @Override
            public void addViewClickListener(View root, MessageBean itemData, int position) {
                super.addViewClickListener(root, itemData, position);
                root.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemData.setRead(true);
                        viewModel.updateMessage(itemData);
                        Toast.makeText(context, StrUtil.toString(itemData), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        dataBinding.rvMessage.setLayoutManager(linearLayoutManager);
        dataBinding.rvMessage.setHasFixedSize(true);//如果每个Item的高度是固定的，设置这个选项可以提供性能
        dataBinding.rvMessage.setItemAnimator(new DefaultItemAnimator());
        dataBinding.rvMessage.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        dataBinding.rvMessage.setAdapter(adapter);
        dataBinding.rvMessage.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                    if (pageIndex < totalPage) {
                        pageIndex += 1;
                    } else {
                        pageIndex = 1;
                    }
                    dataBinding.srlMessage.setRefreshing(true);
                    loadPageData(pageIndex);
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //最后一个可见的item
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        });
    }

    /**
     * 观察数据
     */
    private void observerData() {
        viewModel.messageRepository.dataList.observe(this, new Observer<List<MessageBean>>() {
            @Override
            public void onChanged(List<MessageBean> messageBeans) {
                dataList = messageBeans;
                adapter.setDataList(dataList);
            }
        });
        viewModel.messageRepository.totalCount.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer result) {
                totalPage = (result + PAGE_SIZE - 1) / PAGE_SIZE;
            }
        });
    }

    private void loadPageData(int page) {
        viewModel.getMessageList(PAGE_SIZE, (page - 1) * PAGE_SIZE);
    }
}